package com.example.dryyzx.controller;

import com.example.dryyzx.dao.CustomerMapper;
import com.example.dryyzx.dao.FoodMapper;
import com.example.dryyzx.dao.OrderMapper;
import com.example.dryyzx.entity.Customer;
import com.example.dryyzx.entity.Food;
import com.example.dryyzx.entity.JsonResult;
import com.example.dryyzx.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

@Controller
public class OrderController {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private FoodMapper foodMapper;

    @RequestMapping(value = "food_distribute_page/distribute_food",method = RequestMethod.POST)
    public @ResponseBody
    String addOrder(int cid,String fid,String day,String time){
        Customer currentCustomer = customerMapper.selectByPrimaryKey1(cid);
        if(currentCustomer ==null)
            return new JsonResult(false, "找不到要修改膳食的老人").toString();
        if(currentCustomer.getState().equals("已退住"))
            return new JsonResult(false, "该老人已退住").toString();

        List<Integer> food_id=new ArrayList<Integer>();
        StringTokenizer st = new StringTokenizer(fid,".");
        while(st.hasMoreElements())
            food_id.add(Integer.valueOf(st.nextToken()));
        if(food_id.size()<=0)
            return new JsonResult(false, "请选择食物").toString();
        for(int i=0;i<food_id.size();i++){
            Food currentFood = foodMapper.selectByPrimaryKey(food_id.get(i));
            if(currentFood ==null)
                return new JsonResult(false, "找不到食物").toString();
            if(currentFood.getDay().equals(day)&&currentFood.getTime().equals(time));
            else
                return new JsonResult(false, "食物与返回日期冲突").toString();
        }

        List<Food> foodList = foodMapper.selectByDayTime(day,time);
        int i;
        for(i=0;i<foodList.size();i++){
            int foodId = foodList.get(i).getId();
            int delete = orderMapper.deleteByCidFid(cid,foodId);
        }

        int insert=0;
        for(i=0;i<food_id.size();i++){
            Order tmp=new Order();
            tmp.setCustomerId(cid);
            tmp.setFoodId(food_id.get(i));
            tmp.setEnable(true);
            insert = orderMapper.insertSelective(tmp);
            if(insert==0)
                return new JsonResult(false, "修改膳食失败").toString();
        }
        return new JsonResult(true, insert).toString();
    }
}
